#ifndef _WEB_RADIO_H_
#define _WEB_RADIO_H_

#include <string>
#include <vector>
#include "modules/module.h"

#include <gst/gst.h>
#include <glib.h>

#include "WebStationDataStore.h"

/**
WebRadio get a list of radio (title, address) and starts/stops a thread using gstreamer to play the radio stream
*/
class WebRadio : public module {
public:
    WebRadio(std::shared_ptr<Samsung_20T202DA2JA> screen)
        : module(screen), m_loop(0), m_current_station(0) 
    {init();}
    
    int next();
    int previous();
    
    /** if any stream already loaded, reload it
    usefull when stream was started where there were no connection to internet yet */
    void reload_current_stream();
    
protected:
    std::vector<std::shared_ptr<RadioStation> > m_station_list;
    std::vector<std::shared_ptr<RadioStation> >::iterator m_current_station;
    
    void init();
    
    virtual int threadHandler();
    
    /** thread that run GMainLoop */
    std::thread m_gst_loop_thread;
    /* gst main loop, used for running gst pipeline */
    GMainLoop* m_loop;
    
    //debug trying to solve alsa sink resource busy
    bool m_stream_received_data;
    bool m_async_received;
    bool m_stop_received;
    bool m_test_async_start;
    
    /** start the sreaming thread, that runs the gst loop */
    int start_streaming(const char* addr);
    /** m_gst_loop_thread main function */
    int gst_loop_threadHandler(const char* addr);
    /** stop the sreaming thread, that runs the gst loop
    @noWait defaut false, if true do no wait for straming thread to join */
    int stop_streaming(bool noWait=false);
    
    ////gst data
    /** pipeline used by gst */
    GstElement* m_pipeline;
    /** sink is used in callback function for decoder */
    GstElement* m_audio_sink;
    /** for communication with pipeline */
    GstBus* m_bus;
    
    /** input (bouttons) changed, current stream source be updated 
    this avoids to switch very quickly between station that leads to "alsa resource busy" error */
    bool m_change_station_flag;
    /** time point of the last time m_change_station_flag has been set to true*/
    std::chrono::high_resolution_clock::time_point m_change_station_tp;
    
    /** bus callback for GStreamer Playbin */
    static gboolean bus_callback_s(GstBus* bus, GstMessage* msg, gpointer data);
    /** process a tag (title, artist, etc) received from a stream */
    static void process_one_tag (const GstTagList * list, const gchar * tag, gpointer user_data);
};

#endif
